package com.hunan.api.catv.aop;


import com.hunan.api.catv.annotation.MemberAuth;
import com.hunan.api.catv.common.CacheKey;
import com.hunan.api.catv.entity.Result;
import com.hunan.api.catv.entity.enums.ResultCode;
import com.hunan.api.catv.utils.RedisUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.text.MessageFormat;

@Aspect
@Component
public class MemberAuthAspect {

    private final static Logger log = LoggerFactory.getLogger(MemberAuthAspect.class);

    @Autowired
    RedisUtils redisUtils;

    @Pointcut("@annotation(com.hunan.api.catv.annotation.MemberAuth)")
    public void memberAuthPonitcut() {
    }

    @Around(value = "memberAuthPonitcut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature sign = (MethodSignature) pjp.getSignature();
        Method method = sign.getMethod();
        MemberAuth annotation = method.getAnnotation(MemberAuth.class);
        boolean isAuth = annotation.isAuth();
        if (isAuth) {

            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            //token过期
            if (StringUtils.isEmpty(token)) {
                return new Result(ResultCode.unauthorized.getCode(), ResultCode.unauthorized.getMsg(), "");
            } else {
                String token_key = MessageFormat.format(CacheKey.memberToken, token);
                Object token_result = redisUtils.get(token_key);
                if (ObjectUtils.isEmpty(token_result)) {
                    log.debug("[member login token:{} isEmpty] ", token_key);
                    return new Result(ResultCode.invalid_token.getCode(), ResultCode.invalid_token.getMsg(), "");
                }
                //token未过期，通过验证
                request.setAttribute("memberId", token_result);
            }

        }
        return pjp.proceed();
    }
}